from rest_framework.viewsets import ViewSet
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound
from rest_framework.response import Response
from utils.response import ResponseUtil
from .models import Role
from .serializers import RoleSerializer, RoleCreateUpdateSerializer, PermissionSerializer
from django.contrib.auth.models import Permission


class RoleViewSet(ViewSet):
    """
    角色管理视图集：
    - 创建、修改、删除角色
    - 查询角色信息
    - 分配权限给角色
    """
    permission_classes = [IsAuthenticated]

    def list(self, request):
        """
        查询所有角色列表
        """
        roles = Role.objects.all()
        serializer = RoleSerializer(roles, many=True)
        return ResponseUtil.success(data=serializer.data, message="角色列表获取成功")

    def retrieve(self, request, pk=None):
        """
        查询指定角色详情
        """
        try:
            role = Role.objects.get(pk=pk)
        except Role.DoesNotExist:
            return ResponseUtil.error(code1="1", code2="07", code3="04", message="角色不存在")
        serializer = RoleSerializer(role)
        return ResponseUtil.success(data=serializer.data, message="角色详情获取成功")

    def create(self, request):
        """
        创建新角色
        """
        serializer = RoleCreateUpdateSerializer(data=request.data)
        if serializer.is_valid():
            role = serializer.save()
            return ResponseUtil.success(data=RoleSerializer(role).data, message="角色创建成功")
        return ResponseUtil.error(code1="1", code2="07", code3="01", message="角色创建失败", data=serializer.errors)

    def update(self, request, pk=None):
        """
        更新角色信息
        """
        try:
            role = Role.objects.get(pk=pk)
        except Role.DoesNotExist:
            return ResponseUtil.error(code1="1", code2="07", code3="04", message="角色不存在")

        serializer = RoleCreateUpdateSerializer(role, data=request.data, partial=True)
        if serializer.is_valid():
            updated_role = serializer.save()
            return ResponseUtil.success(data=RoleSerializer(updated_role).data, message="角色更新成功")
        return ResponseUtil.error(code1="1", code2="07", code3="02", message="角色更新失败", data=serializer.errors)

    def destroy(self, request, pk=None):
        """
        删除指定角色
        """
        try:
            role = Role.objects.get(pk=pk)
        except Role.DoesNotExist:
            return ResponseUtil.error(code1="1", code2="07", code3="04", message="角色不存在")

        role.delete()
        return ResponseUtil.success(message=f"角色 {pk} 删除成功")

    @action(detail=True, methods=['post'])
    def assign_permissions(self, request, pk=None):
        """
        分配权限给指定角色
        """
        try:
            role = Role.objects.get(pk=pk)
        except Role.DoesNotExist:
            return ResponseUtil.error(code1="1", code2="07", code3="04", message="角色不存在")

        permission_ids = request.data.get("permission_ids", [])
        if not isinstance(permission_ids, list):
            return ResponseUtil.error(code1="1", code2="07", code3="01", message="权限ID列表格式不正确")

        # 清除现有权限
        role.permissions.clear()

        # 添加新权限
        assigned_permissions = []
        for permission_id in permission_ids:
            try:
                permission = Permission.objects.get(id=permission_id)
                role.permissions.add(permission)
                assigned_permissions.append(permission)
            except Permission.DoesNotExist:
                return ResponseUtil.error(code1="1", code2="06", code3="04", message=f"权限ID {permission_id} 不存在")

        return ResponseUtil.success(
            data=PermissionSerializer(assigned_permissions, many=True).data,
            message="权限分配成功"
        )

    @action(detail=False, methods=['get'])
    def permissions(self, request):
        """
        获取所有权限列表
        """
        permissions = Permission.objects.all()
        serializer = PermissionSerializer(permissions, many=True)
        return ResponseUtil.success(data=serializer.data, message="权限列表获取成功")
